package com.yang.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.yang.entity.User;
import com.yang.service.UserService;

public class IndexAction extends ActionSupport implements SessionAware{

	private static final long serialVersionUID = -1265071775034868973L;
	private InputStream inputStream;
	private String name;
	private String password;
	private UserService us = new UserService();
	private Map<String,Object> session;

	@Action(value = "index", results = { @Result(name = "success", type = "redirect", location = "/index.jsp") })
	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}

	@Action(value = "login", results = { @Result(name = SUCCESS, type = "stream", params = {
			"contentType", "text/html", "inputName", "inputStream" }) })
	public String login() throws Exception {
		password=DigestUtils.md5Hex(password);
		User user = us.findByNameAndPassword(name, password);
		if (user != null) {
			session.put("user",user);
			inputStream = new ByteArrayInputStream("ok".getBytes());
		} else {
			inputStream = new ByteArrayInputStream("error".getBytes());
		}
		return SUCCESS;
	}
	
	@Action(value = "reg", results = { @Result(name = SUCCESS, type = "stream", params = {
			"contentType", "text/html", "inputName", "inputStream" }) })
	public String reg() throws Exception {
		User user = us.findByNameAndPassword(name, null);
		if (user != null) {
			inputStream = new ByteArrayInputStream("error".getBytes());
		} else {
			inputStream = new ByteArrayInputStream("ok".getBytes());
		}
		return SUCCESS;
	}
	@Action(value = "regret", results = { @Result(name = SUCCESS, type = "stream", params = {
			"contentType", "text/html", "inputName", "inputStream" }) })
	public String regret() throws Exception {
		UUID uu=UUID.randomUUID();
		String id=uu.toString();
		password=DigestUtils.md5Hex(password);
		User user = us.insertByNameAndPassword(id,name, password);
		if (user != null) {
			session.put("user",user);
			inputStream = new ByteArrayInputStream("ok".getBytes());
		} else {
			inputStream = new ByteArrayInputStream("error".getBytes());
		}
		return SUCCESS;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public void setSession(Map<String, Object> map) {
		session=map;
	}

}
